<!--
/**
* @description 区域管理
* @author mdong
* @date 2020-05-11
*/
-->
<template>
  <div class="organization">
    <section class="organization-tree">
      <!-- 左侧树状图 -->
      <div class="tree-content">
        <a-tree :show-line="showLine"
                :show-icon="true"
                :tree-data="treeData"
                :auto-expand-parent="true "
                :replace-fields="replaceFields"
                @select="onSelect">
          <template slot="custom-folder" slot-scope="{ expanded }">
            <a-icon :type="expanded ? 'folder-open' : 'folder'" theme="filled"/>
          </template>
        </a-tree>
      </div>
    </section>
    <div class="index-right-box">
      <!-- 右侧查询 -->
      <a-form-model ref="searchForm"
                    class="index-search-form-model"
                    :model="searchForm"
                    layout="inline"
      >
        <a-form-model-item label="区域名称"
                           prop="name">
          <a-input v-model="searchForm.name"
                   allowClear
                   placeholder="请输入区域名称">
          </a-input>
        </a-form-model-item>
        <a-form-model-item class="top-widget-btn">
          <a-button type="primary"
                    icon="search"
                    shape="round"
                    @click="queryListBycondition">查询</a-button>
          <a-button icon="retweet"
                    shape="round"
                    @click="resetList">重置</a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 顶部控件 -->
      <section class="table-list">
        <div class="table-opt-btns">
          <!-- 操作按钮 -->
          <a-button type="primary"
                    :disabled="!currSelTreeNode.id"
                    icon="plus"
                    @click="addOrganization">新增</a-button>
        </div>
        <!-- 表格操作 -->
        <a-table :columns="columns"
                 :customRow="tableCustomRow"
                 :dataSource="tableDdata"
                 bordered
                 :loading="tableLoading"
                 rowKey="id"
                 @change="tableChange"
                 :pagination="pagination">
          <div slot="operation"
               slot-scope="text,record,index"
               class="tabe-button">
            <a-button size="small"
                      type="primary"
                      icon="edit"
                      @click="editData(text, record, index)">编辑</a-button>
            <a-button size="small"
                      type="danger"
                      icon="close"
                      @click="delData(text, record, index)">删除</a-button>
          </div>
        </a-table>
        <!-- 表格 -->
        <!-- 新增编辑表格 -->
        <operate-form :operateVisible="operateVisible"
                      :confirmLoading="confirmLoading"
                      :operateData="operateData"
                      :optType="optType"
                      @handidleSubmit="operateSubmit"
                      @handleVisible="handleOperateTableVisible"></operate-form>
        <!-- 新增编辑表格 -->
      </section>
    </div>
  </div>
</template>

<script>
import { orgColumns } from '@/utils/columns'
import { FormModel, Tree, Input, Button, Table, Icon } from 'ant-design-vue'
import { queryOrgTree, queryOrgListByPage, delOrg, addOrg, updateOrg } from '@/request/api/permissionManagement/org'
import OperateForm from './components/OperateForm'
import { getFinalPageNo, getCustomIconTreeData } from '@/utils/index'
// 找到节点自身及上级子节点们的集合
const getSelIds = (treeData, idValue, parentKey, idKey, rootPIdValue = null, childrenKey = 'children') => {
  const selResult = []
  function findSel (data, id) {
    let isFind = false
    for (const i of data) {
      if (isFind) {
        break
      }
      if (i[idKey] !== id) {
        if ((undefined !== i[childrenKey]) && (i[childrenKey] !== null)) {
          if (i[parentKey] && i[parentKey] !== rootPIdValue) {
            selResult.push(i[parentKey])
          }
          isFind = findSel(i[childrenKey], id)
        }
      } else {
        if (i[parentKey] && i[parentKey] !== rootPIdValue) {
          selResult.push(i[parentKey])
        }
        selResult.push(id)
        isFind = true
      }
    }
    if (!isFind) {
      selResult.pop()
    }
    return isFind
  }
  findSel(treeData, idValue)
  return selResult
}
export default {
  name: 'organization',
  components: {
    ATree: Tree,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    AButton: Button,
    ATable: Table,
    OperateForm: OperateForm,
    AIcon: Icon
  },
  data () {
    return {
      searchForm: {
        name: ''
      },
      // 点击树状图的id
      orgId: null,
      // 编辑和删除的附加点id
      opreateParentId: null,
      replaceFields: {
        children: 'childrenList',
        title: 'name',
        key: 'id'
      },
      // 树状图数据
      treeData: [],
      // 树状图配置
      showLine: true,
      showIcon: false,
      formLayout: 'horizontal',
      // 角色表头
      columns: orgColumns,
      // 表数据
      tableDdata: [],
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 是否打开新增和编辑抽屉
      operateVisible: false,
      optType: 'add',
      // 新增和编辑抽屉数据
      operateData: {
        parentName: '',
        code: '',
        name
      },
      // 当前点击树节点
      currSelTreeNode: {},
      // 弹框提交按钮loading
      confirmLoading: false
    }
  },
  created () {
    this.getOrgTree()
    this.queryListByPage()
  },
  methods: {
    // table自定义事件
    tableCustomRow (record) {
      return {
        on: { // 事件
          dblclick: (event) => {
            this.optType = 'view'
            this.opreateParentId = record.parentId
            this.operateData = Object.assign({}, {
              id: record.id
            })
            this.operateVisible = true
          }
        }
      }
    },
    // 检查某id下是否存在children
    checkTreeIdIsHaveChild (treeData, idValue, idKey = 'id') {
      const listData = []
      function fnc (tree) {
        tree.forEach((p) => {
          listData.push(p)
          if (p.childrenList && (p.childrenList.length > 0)) {
            fnc(p.childrenList)
          }
        })
      }
      fnc(treeData)
      const target = listData.find((item) => item[idKey] === idValue)
      if (target) {
        if (target.childrenList && target.childrenList.length) {
          return true
        }
      }
    },
    // 查询左侧树形结构数据
    getOrgTree () {
      const params = {}
      queryOrgTree(params).then((res) => {
        if (res.code === '0') {
          this.treeData = getCustomIconTreeData(res.data, 'childrenList')
        }
      })
    },
    // 点击树状图
    onSelect (selectedKeys, info) {
      this.pagination.current = 1
      if (!selectedKeys.length) {
        this.currSelTreeNode = {}
        this.queryDataByPage(this.searchForm)
        return
      }
      this.currSelTreeNode = info.selectedNodes[0].data.props
      this.orgId = selectedKeys
      this.operateData.parentName = info.node.title
      this.queryDataByPage(this.searchForm)
    },
    // 查询数据
    queryDataByPage (query) {
      if (this.currSelTreeNode.id) {
        query = {
          parentId: this.currSelTreeNode.id, // 后端定义 当前点击id 传给后端作为parentId字段
          ...query
        }
      }
      this.tableLoading = true
      const params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        param: query
      }
      queryOrgListByPage(params).then((res) => {
        this.tableLoading = false
        if (res.code === '0') {
          this.tableDdata = res.data.list
          this.pagination.total = res.data.total
        } else {
          this.tableDdata = []
          this.pagination.total = 0
        }
      }).catch(error => {
        this.tableLoading = false
        console.log(error)
      })
    },
    // 默认查询
    queryListByPage () {
      const params = {}
      this.queryDataByPage(params)
    },
    // 表格变动分页查询
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      const params = {}
      this.queryDataByPage(params)
      // 查询接口
    },
    // 重置
    resetList () {
      this.pagination.current = 1
      this.$refs.searchForm.resetFields()
      this.queryListByPage()
    },
    // 条件查询
    queryListBycondition () {
      this.pagination.current = 1
      this.queryDataByPage(this.searchForm)
    },
    // 提交新增和编辑表单
    async operateSubmit (params) {
      this.confirmLoading = true
      if (this.optType === 'add') {
        const parentIds = getSelIds(this.treeData, this.currSelTreeNode.id, 'parentId', 'id', this.treeData[0].parentId, 'childrenList').join() + ','
        const query = {
          parentId: this.orgId[0],
          name: params.name,
          code: params.code,
          parentIds
        }
        await addOrg(query).then((res) => {
          if (res.code === '0') {
            this.$message.success('新增成功!')
            this.resetList()
            this.getOrgTree()
            this.operateVisible = false
          }
        }).catch(() => {
        })
      } else {
        await updateOrg(params).then((res) => {
          if (res.code === '0') {
            this.$message.success('编辑成功!')
            this.queryDataByPage(this.searchForm)
            this.operateVisible = false
            this.getOrgTree()
          }
        }).catch(() => {
        })
      }
      this.confirmLoading = false
    },
    // 关闭新增和编辑抽屉
    handleOperateTableVisible (parms) {
      this.operateVisible = false
    },
    // 新增区域
    addOrganization () {
      if (this.orgId) {
        this.operateVisible = true
        this.optType = 'add'
        this.operateData.code = ''
        this.operateData.name = ''
        this.operateData.parentName = this.currSelTreeNode.title
      } else {
        this.$message.error('请先选择区域!')
        return false
      }
    },
    editData (text, record, index) {
      this.opreateParentId = record.parentId
      this.operateData = Object.assign({}, {
        id: record.id
      })
      this.optType = 'edit'
      this.operateVisible = true
    },
    // 删除数据
    delData (text, record, index) {
      this.opreateParentId = record.parentId
      this.$confirm({
        title: '删除之后无法恢复，确定要删除数据吗?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          const isHaveChild = this.checkTreeIdIsHaveChild(this.treeData, record.id)
          if (isHaveChild) {
            this.$message.warn('当前删除项存在子节点')
            return
          }
          const params = { id: record.id }
          delOrg(params).then((res) => {
            if (res.code === '0') {
              this.$message.success('删除成功!')
              this.pagination.current = getFinalPageNo(
                this.pagination.total,
                this.pagination.current,
                this.pagination.pageSize,
                1)
              this.queryDataByPage(this.searchForm)
              this.getOrgTree()
            }
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.organization {
  width: 100%;
  height: 100%;
  display: flex;
  .organization-tree {
    min-width: 256px;
    background-color: #ffffff;
    margin-right: 20px;
    padding: 20px;
    box-sizing: border-box;
    .tree-content {
      height: 100%;
      overflow-y: auto;
    }
  }
  .table-list {
    background-color: #ffffff;
    padding: 20px;
    box-sizing: border-box;
  }
}
</style>
